from apps.HttpTestcase.models import Testsuite
from apps.HttpTestcase.serializers.testsuite import TestSuiteSerializer, TestCreatsuiteSerializer, TestsuiteNamesSerializer
from apps.HttpTestcase.core.utils import get_version
from apps.CeleryTimedTask.HttpTestcase.testsuite_task import batch_exec_testsuite
from apps.HttpTestcase.filters.testsuite import TestsuiteFilters, TestsuiteNamesFilters

from rest_framework import permissions
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.mixins import CreateModelMixin
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework.views import APIView
from rest_framework.generics import DestroyAPIView
from utils.response import *
from utils.viewsets import *


class TestsuiteNames(ReadOnlyModelViewSet):
    serializer_class = TestsuiteNamesSerializer
    filter_class = TestsuiteNamesFilters

    def get_queryset(self):
        testsuite = Testsuite.objects.values().filter(is_delete=False)
        # res_list = list(testsuite)
        return testsuite


class TestsuiteList(ReadOnlyModelViewSet):
    queryset = Testsuite.objects.filter(is_delete=False)
    serializer_class = TestSuiteSerializer
    filter_fields = ['id', 'name']
    filter_class = TestsuiteFilters
    permission_classes = [permissions.IsAuthenticated]


class TestsuiteViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet, DestroyModelMixin):
    """
    创建、更新、修改
    """
    queryset = Testsuite.objects.filter(is_delete=False)
    serializer_class = TestCreatsuiteSerializer

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()  # 逻辑删除


class TestsuiteBatchAPIView(APIView):
    def post(self, request, *args, **kwargs):
        pass
        data = request.data
        testsuites = data.get('testsuites')
        version = get_version()
        batch_exec_testsuite(testsuites=testsuites, version=version)
        return SuccessResponse(data=None, msg='程序正在后台运行中,请稍后查看结果……')


class TestsuiteDelete(DestroyAPIView):
    def delete(self, request, *args, **kwargs):
        is_de = request.data.get('is_de')
        testsuite_id = request.data.get('testsuite_id')
        testsuite_ids = []
        for item in testsuite_id:
            testsuite_ids.append(item.get('id'))
        if is_de:
            Testsuite.objects.filter(id__in=testsuite_ids).delete()
        else:
            Testsuite.objects.filter(id__in=testsuite_ids).update(is_delete=True)

        return SuccessResponse(data=None, msg='删除成功!')